from datetime import datetime
from typing import Optional, Dict, Any
from pydantic import BaseModel, Field, field_validator
from app.core.constants import StorageProviderEnum


class StorageProviderBase(BaseModel):
    """存储供应商基础模型"""

    name: str = Field(..., description="供应商名称", min_length=2, max_length=50)
    type: StorageProviderEnum = Field(..., description="供应商类型")
    config: Dict[str, Any] = Field(..., description="配置信息")
    is_default: bool = Field(False, description="是否为默认供应商")

    @field_validator("config")
    def validate_config(cls, v: Dict[str, Any], values: Dict[str, Any]) -> Dict[str, Any]:
        """验证配置信息"""
        provider_type = values.get("type")
        if not provider_type:
            return v

        # 验证必需的配置字段
        required_fields = {
            StorageProviderEnum.LOCAL: ["base_path", "base_url"],
            StorageProviderEnum.ALIYUN_OSS: ["access_key", "secret_key", "bucket", "endpoint"],
            StorageProviderEnum.AWS_S3: ["access_key", "secret_key", "bucket", "region"],
            StorageProviderEnum.TENCENT_COS: ["secret_id", "secret_key", "bucket", "region"],
        }

        missing_fields = [field for field in required_fields[provider_type] if field not in v]
        if missing_fields:
            raise ValueError(f"缺少必需的配置字段: {', '.join(missing_fields)}")

        return v


class AdminStorageProviderCreate(StorageProviderBase):
    """创建存储供应商请求"""

    pass


class AdminStorageProviderUpdate(BaseModel):
    """更新存储供应商请求"""

    id: int = Field(..., description="供应商ID")
    name: Optional[str] = Field(None, description="供应商名称", min_length=2, max_length=50)
    config: Optional[Dict[str, Any]] = Field(None, description="配置信息")
    is_default: Optional[bool] = Field(None, description="是否为默认供应商")


class AdminStorageProviderResponse(StorageProviderBase):
    """存储供应商响应"""

    id: int = Field(..., description="供应商ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    file_count: int = Field(0, description="文件数量")

    class Config:
        from_attributes = True


class AdminStorageProviderDetail(AdminStorageProviderResponse):
    """存储供应商详情"""

    total_size: int = Field(0, description="总存储大小(字节)")
    used_size: int = Field(0, description="已用存储大小(字节)")
    file_count_by_type: Dict[str, int] = Field(default_factory=dict, description="各类型文件数量")
    connection_status: bool = Field(False, description="连接状态")

class AdminStorageProviderListFilter(BaseModel):
    """存储供应商列表过滤条件"""

    name: Optional[str] = Field(None, description="供应商名称")
    type: Optional[StorageProviderEnum] = Field(None, description="供应商类型")
